package xyz.syyrjx.blog.service.impl;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.dao.type.TypeDao;
import xyz.syyrjx.blog.entity.Types;
import xyz.syyrjx.blog.exception.DeleteException;
import xyz.syyrjx.blog.service.TypeService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
    @Resource
    private TypeDao dao;

    @Override
    public boolean addType(String name) {
        boolean res = false;
        Types template = new Types();
        template.setState(State.NORMAL_STATE.getCode());
        List<Types> types = dao.selectType(template,null,null);
        boolean isHave = false;
        for(Types temp : types){
            if(name.equals(temp.getName())){
                isHave = true;
                break;
            }
        }
        if(!isHave){
            Types type = new Types(null, name);
            if(dao.insertType(type) > 0){
                res = true;
            }

        }
        return res;
    }

    @Override
    public int countTypes() {
        return dao.countTypes();
    }


    @Override
    public Types queryTypeById(Long id) {
        Types template = new Types();
        template.setId(id);
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectType(template,null,null).get(0);
    }

    @Override
    public List<Types> queryAllTypes() {
        Types template = new Types();
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectType(template,null,null);
    }

    @Override
    public List<Types> queryTypesInPage(Integer page) {
        Integer start = null;
        Integer num = null;
        if (page != null){
            start = (page - 1) * 10;
            num = 10;
        }
        Types template = new Types();
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectType(template, start,num);
    }

    @Override
    public boolean updateType(Types type) {
        boolean flag = false;
        if(dao.updateType(type) > 0){
            flag = true;
        }
        return flag;
    }

    @Override
    @Transactional
    public boolean deleteType(Types type) {
        int delRes = dao.deleteType(type);
        return true;
    }
}
